/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amit.collections;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author amit
 */
public class CountingMap extends ConcurrentHashMap<String, Float> implements Serializable {

    public static class CountAndString implements Comparator, Serializable {

        public String data;
        public float count;

        public CountAndString(String data, float count) {
            this.data = data;
            this.count = count;
        }

        public float getCount() {
            return count;
        }

        public String getData() {
            return data;
        }

        @Override
        public String toString() {
            return "CountAndString: " + data.toString() + " - " + count;
        }

        public int compare(Object o1, Object o2) {
            float i1 = ((CountAndString) o1).count;
            float i2 = ((CountAndString) o2).count;
            return Float.compare(i1, i2);
        }
    }

    public synchronized float getCountAndIncrement(String key) {
        Float value = get(key);
        if (value == null) {
            value = 1F;
        } else {
            value++;
        }
        put(key, value);
        return value;
    }

    public float getCountAndAdd(String key, float increment) {
        Float value = get(key);
        if (value == null) {
            value = increment;
        } else {
            value += increment;
        }
        put(key, value);
        return value;
    }

    public ArrayList<CountAndString> getSortedList(Comparator c) {
        ArrayList<CountAndString> toReturn = new ArrayList<CountAndString>(size());
        for (String key : keySet()) {
            toReturn.add(new CountAndString(key, get(key)));
        }
        Collections.sort(toReturn, c);
        return toReturn;
    }

    public ArrayList<CountAndString> getSortedList() {
        ArrayList<CountAndString> toReturn = new ArrayList<CountAndString>(size());
        for (String key : keySet()) {
            toReturn.add(new CountAndString(key, get(key)));
        }
        if (toReturn.size() > 0) {
            Collections.sort(toReturn, (Comparator) toReturn.get(0));
        }
        return toReturn;
    }
}
